export async function uploadBlob(blobUrl, cloudPath) {
  try {
    // 1. 获取 Blob 对象
    const response = await fetch(blobUrl);
    const blob = await response.blob();
    
    // 2. 生成文件名
    const fileExt = getFileExtension(cloudPath) || getFileExtensionFromType(blob.type);
    const fileName = `${Date.now()}.${fileExt}`;
    
    // 3. 根据环境选择不同的上传策略
    let fileID;
    if (isInMiniProgram()) {
      // 小程序环境：使用 uni-app 文件系统 API
      const filePath = await saveBlobToFileInMiniProgram(blob, fileName);
      const result = await uniCloud.uploadFile({
        filePath,
        cloudPath: cloudPath || `upload/${fileName}`,
        fileType: getFileType(blob.type)
      });
      fileID = result.fileID;
    } else {
      // 浏览器环境：使用 webUploadFile 配合 FormData
      fileID = await uploadInBrowser(blob, cloudPath || `upload/${fileName}`);
    }
    
    console.log("上传成功:", fileID);
    return { success: true, fileID };
  } catch (error) {
    console.error("上传失败:", error);
    return { success: false, error: error.message };
  }
}

// 判断是否在小程序环境
function isInMiniProgram() {
  try {
    return typeof uni !== 'undefined' && typeof uni.getFileSystemManager === 'function';
  } catch (e) {
    return false;
  }
}

// 在小程序环境中保存 Blob 到文件
function saveBlobToFileInMiniProgram(blob, fileName) {
  return new Promise((resolve, reject) => {
    const fs = uni.getFileSystemManager();
    const tempFilePath = `${uni.env.USER_DATA_PATH}/${fileName}`;
    
    fs.writeFile({
      filePath: tempFilePath,
      data: blob,
      encoding: 'binary',
      success: () => resolve(tempFilePath),
      fail: (err) => reject(new Error(`文件保存失败: ${err.errMsg}`))
    });
  });
}

// 在浏览器环境中上传 Blob
async function uploadInBrowser(blob, cloudPath) {
  return new Promise((resolve, reject) => {
    // 创建 FormData 对象
    const formData = new FormData();
    formData.append('file', blob, cloudPath);
    
    // 使用 uniCloud.webUploadFile
    uniCloud.webUploadFile({
      url: `https://${uniCloud.config.serviceId}.service.tcloudbase.com/upload`,
      formData: formData,
      success: (res) => {
        if (res.code === 0 && res.fileID) {
          resolve(res.fileID);
        } else {
          reject(new Error(`上传失败: ${res.message || '未知错误'}`));
        }
      },
      fail: (err) => {
        reject(new Error(`上传失败: ${err.errMsg}`));
      }
    });
  });
}

// 辅助函数：获取文件扩展名
function getFileExtension(filePath) {
  if (!filePath) return '';
  const ext = filePath.split('.').pop();
  return ext ? ext.toLowerCase() : '';
}

// 辅助函数：从 MIME 类型获取文件扩展名
function getFileExtensionFromType(mimeType) {
  const extMap = {
    'image/jpeg': 'jpg',
    'image/png': 'png',
    'image/gif': 'gif',
    'image/webp': 'webp',
    'video/mp4': 'mp4',
    'audio/mpeg': 'mp3'
  };
  return extMap[mimeType] || 'file';
}

// 辅助函数：获取文件类型
function getFileType(mimeType) {
  if (mimeType.startsWith('image/')) return 'image';
  if (mimeType.startsWith('video/')) return 'video';
  if (mimeType.startsWith('audio/')) return 'audio';
  return 'file';
}